package com.yc;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class WeatherMailScheduler {
    // 心知天气API配置
    private static final String API_KEY = "S9ABcP7or9ROC1lzu";
    private static final String API_URL = "https://api.seniverse.com/v3/weather/now.json";

    // QQ邮箱配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final int SMTP_PORT = 465;
    private static final String EMAIL_FROM = "2381501220@qq.com";
    private static final String EMAIL_PASSWORD = "aohstiyriieceabi";

    // 接收者邮箱列表（可添加多个）
    private static final String[] RECIPIENTS = {
            "2239129909@qq.com",
            "1990668148@qq.com",
            "2381501220@qq.com"
    };

    // 定时任务执行时间（每天8:00）
    private static final String CRON_TIME = "0 0 17 * * ?";

    public static void main(String[] args) {
        try {
            // 初始化定时任务
            WeatherTimer weatherTimer = new WeatherTimer();
            weatherTimer.scheduleDailyWeatherMail(CRON_TIME, RECIPIENTS);
            System.out.println("天气邮件定时任务已启动，每天" + CRON_TIME + "执行");
        } catch (ParseException e) {
            System.err.println("定时任务配置错误: " + e.getMessage());
        }
    }

    // 天气API客户端
    public static class WeatherApiClient {

        public WeatherResponse getWeather(String location, String unit) throws IOException {
            OkHttpClient client = new OkHttpClient();
            HttpUrl httpUrl = HttpUrl.parse(API_URL).newBuilder()
                    .addQueryParameter("key", API_KEY)
                    .addQueryParameter("location", location)
                    .addQueryParameter("language", "zh-Hans")
                    .addQueryParameter("unit", unit)
                    .build();
            Request request = new Request.Builder().url(httpUrl).build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("API请求失败: " + response);
                String jsonData = response.body().string();
                return new Gson().fromJson(jsonData, WeatherResponse.class);
            }
        }
    }

    // 邮件发送器
    public static class QQMailSender {
        public void sendWeatherMail(String recipient, String city) throws MessagingException, IOException {
            // 获取天气数据
            WeatherResponse response = new WeatherApiClient().getWeather(city, "c");
            if (response == null || response.getResults().isEmpty()) {
                throw new IllegalStateException("获取天气数据失败");
            }
            WeatherResult result = response.getResults().get(0);

            // 配置邮件
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.debug", "false");

            Session session = Session.getInstance(props, new Authenticator() {
                @Override protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(EMAIL_FROM, EMAIL_PASSWORD);
                }
            });

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(EMAIL_FROM));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
            message.setSubject(result.getLocation().getName() + " 维哥超级爱心天气通知");

            // 构建带动画和爱心的邮件内容（与之前一致）
            String content = "<html>" +
                    "<head>" +
                    "<title>维哥超级爱心天气通知</title>" +
                    "<style>" +
                    "/* 定义爱心动画 */" +
                    "@keyframes heartBeat {" +
                    "  0% { transform: scale(1); opacity: 1; }" +
                    "  14% { transform: scale(1.3); opacity: 0.9; }" +
                    "  28% { transform: scale(1); opacity: 1; }" +
                    "  42% { transform: scale(1.3); opacity: 0.9; }" +
                    "  70% { transform: scale(1); opacity: 1; }" +
                    "}" +
                    "@keyframes float {" +
                    "  0%, 100% { transform: translateY(0); }" +
                    "  50% { transform: translateY(-10px); }" +
                    "}" +
                    ".heart {" +
                    "  color: #ff69b4; /* 粉红色爱心 */" +
                    "  animation: heartBeat 1.8s infinite;" +
                    "  font-size: 1.8em;" +
                    "  display: inline-block;" +
                    "  vertical-align: middle;" +
                    "}" +
                    ".floating-heart {" +
                    "  color: #ff4585; /* 渐变爱心 */" +
                    "  animation: float 3s infinite ease-in-out;" +
                    "  font-size: 1.5em;" +
                    "  margin: 0 8px;" +
                    "}" +
                    ".red-text {" +
                    "  color: #e74c3c; /* 红色字体 */" +
                    "  font-weight: bold;" +
                    "  text-shadow: 1px 1px 2px rgba(231, 76, 60, 0.3);" +
                    "}" +
                    ".weather-card {" +
                    "  background: linear-gradient(135deg, #fff9f9, #fce8f0);" +
                    "  border-radius: 16px;" +
                    "  padding: 25px;" +
                    "  box-shadow: 0 8px 15px rgba(255, 105, 180, 0.1);" +
                    "  border-left: 5px solid #ff69b4;" +
                    "  transition: all 0.4s ease;" +
                    "}" +
                    ".weather-card:hover {" +
                    "  transform: translateY(-8px);" +
                    "  box-shadow: 0 12px 25px rgba(255, 105, 180, 0.15);" +
                    "}" +
                    ".love-message {" +
                    "  color: #e74c3c;" +
                    "  font-size: 16px;" +
                    "  font-style: italic;" +
                    "  margin: 20px 0;" +
                    "  line-height: 1.6;" +
                    "  text-align: center;" +
                    "}" +
                    ".signature {" +
                    "  color: #ff4585;" +
                    "  font-weight: bold;" +
                    "  font-size: 18px;" +
                    "  text-align: right;" +
                    "  margin-top: 30px;" +
                    "  letter-spacing: 1px;" +
                    "}" +
                    "</style>" +
                    "</head>" +
                    "<body style=\"font-family: 'Microsoft YaHei', 'Apple Color Emoji', Arial, sans-serif; max-width: 650px; margin: 0 auto; padding: 25px; background-color: #fef5f7; padding-bottom: 50px;\">" +

                    "<!-- 顶部爱心装饰 -->" +
                    "<div style=\"text-align: center; margin-bottom: 15px; position: relative;\">" +
                    "  <span class=\"floating-heart\" style=\"animation-delay: 0.2s;\">♥</span>" +
                    "  <span class=\"floating-heart\" style=\"animation-delay: 0.5s;\">♥</span>" +
                    "  <span class=\"floating-heart\" style=\"animation-delay: 0.8s;\">♥</span>" +
                    "</div>" +

                    "<!-- 标题区域 -->" +
                    "<div style=\"text-align: center; margin-bottom: 25px;\">" +
                    "  <span class=\"heart\">♥</span>" +
                    "  <h1 style=\"color: #e74c3c; display: inline-block; margin: 0 15px; font-size: 24px; font-weight: bold;\">" +
                    "    维哥超级爱心天气通知" +
                    "  </h1>" +
                    "  <span class=\"heart\">♥</span>" +
                    "</div>" +

                    "<!-- 天气卡片 -->" +
                    "<div class=\"weather-card\">" +
                    "  <h2 style=\"color: #2c3e50; margin-top: 0; display: flex; align-items: center;\">" +
                    "    " + result.getLocation().getName() + " " +
                    "    <span class=\"red-text\" style=\"margin-left: 10px;\">维哥</span>" +
                    "    <span class=\"heart\" style=\"margin-left: 5px;\">♥</span>" +
                    "    超级爱心天气通知" +
                    "  </h2>" +
                    "  <p style=\"margin-top: 15px;\"><strong><span class=\"red-text\">维哥提醒您</span> <span class=\"heart\" style=\"font-size: 1.2em;\">❤️</span>:</strong> 当前天气: " +
                    "    <span style=\"font-size: 1.1em; color: #3498db;\">" + result.getNow().getText() + "</span>" +
                    "  </p>" +
                    "  <p><strong>当前温度:</strong> " +
                    "    <span style=\"font-size: 1.3em; color: #e74c3c; font-weight: bold;\">" + result.getNow().getTemperature() + "°C</span> " +
                    "    <span class=\"heart\">♥</span>" +
                    "  </p>" +
                    "  <p><strong>更新时间:</strong> " + result.getLastUpdate() + "</p>" +

                    "  <!-- 温馨提示 -->" +
                    "  <div style=\"margin-top: 20px; padding-top: 15px; border-top: 1px dashed #ffccd5;\">" +
                    "    <p style=\"color: #ff4585; font-size: 14px;\">" +
                    "      <span class=\"heart\" style=\"font-size: 1.1em;\">♥</span> 今天也要记得多喝水，想你的维哥一直在哦~" +
                    "    </p>" +
                    "  </div>" +
                    "</div>" +

                    "<!-- 爱情元素增强区 -->" +
                    "<div style=\"text-align: center; margin: 30px 0;\">" +
                    "  <div class=\"love-message\">" +
                    "    即使天气会变，但我对你的爱永远恒温在37℃，" + "<br>" +
                    "    就像今天的阳光，每一缕都想照在你身上~" +
                    "  </div>" +
                    "  <div style=\"font-size: 30px; margin: 20px 0;\">" +
                    "    <span class=\"heart\" style=\"animation-delay: 0.3s;\">♥</span>" +
                    "    <span class=\"heart\" style=\"animation-delay: 0.6s;\">♥</span>" +
                    "    <span class=\"heart\" style=\"animation-delay: 0.9s;\">♥</span>" +
                    "    <span class=\"heart\" style=\"animation-delay: 1.2s;\">♥</span>" +
                    "    <span class=\"heart\" style=\"animation-delay: 1.5s;\">♥</span>" +
                    "  </div>" +
                    "  <p style=\"color: #7f8c8d; font-size: 14px;\">数据来源: <span class=\"red-text\">专属维哥的爱</span> API</p>" +
                    "</div>" +

                    "<!-- 签名区域 -->" +
                    "<div class=\"signature\">" +
                    "  <span class=\"heart\" style=\"font-size: 1.5em;\">♥</span>" +
                    "  永远爱你的维哥" +
                    "  <span class=\"heart\" style=\"font-size: 1.5em;\">♥</span>" +
                    "</div>" +

                    "<!-- 底部爱心动画 -->" +
                    "<div style=\"text-align: center; position: relative; margin-top: 40px;\">" +
                    "  <span class=\"floating-heart\" style=\"animation-delay: 0.4s;\">♥</span>" +
                    "  <span class=\"floating-heart\" style=\"animation-delay: 0.7s;\">♥</span>" +
                    "  <span class=\"floating-heart\" style=\"animation-delay: 1.0s;\">♥</span>" +
                    "</div>" +
                    "</body>" +
                    "</html>";

            message.setContent(content, "text/html; charset=utf-8");
            Transport.send(message);
        }
    }

    // 定时任务管理器
    public static class WeatherTimer {
        private final Timer timer = new Timer("Weather-Mail-Timer");

        /**
         * 按Cron表达式 schedule 定时任务
         * @param cronExpression Cron表达式（如每天8点：0 0 8 * * ?）
         * @param recipients 收件人邮箱数组
         */
        public void scheduleDailyWeatherMail(String cronExpression, String[] recipients) throws ParseException {
            // 解析Cron表达式
            CronExpression cron = new CronExpression(cronExpression);
            // 计算下次执行时间
            Date nextExecutionTime = cron.getNextExecutionTime(new Date());

            // 为每个收件人创建定时任务
            for (String recipient : recipients) {
                // 提取城市（实际应用中可从数据库或配置文件获取城市-邮箱映射）
                String city = getCityByEmail(recipient);

                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            new QQMailSender().sendWeatherMail(recipient, city);
                            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +
                                    " 已发送天气邮件至: " + recipient);
                        } catch (Exception e) {
                            System.err.println("发送邮件失败 to " + recipient + ": " + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }, nextExecutionTime);

                // 添加日志
                System.out.println("已为 " + recipient + " 安排天气邮件任务，下次执行时间: " +
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextExecutionTime));
            }
        }

        // 模拟：根据邮箱获取对应城市（实际应用中可从数据库查询）
        private String getCityByEmail(String email) {
            // 示例：根据邮箱后缀或前缀映射城市
            if (email.contains("shanghai")) return "上海";
            if (email.contains("beijing")) return "北京";
            return "广州"; // 默认城市
        }
    }

    // 数据模型类
    public static class WeatherResponse {
        @SerializedName("results") private List<WeatherResult> results;
        public List<WeatherResult> getResults() { return results; }
    }

    public static class WeatherResult {
        @SerializedName("location") private Location location;
        @SerializedName("now") private WeatherNow now;
        @SerializedName("last_update") private String lastUpdate;
        public Location getLocation() { return location; }
        public WeatherNow getNow() { return now; }
        public String getLastUpdate() { return lastUpdate; }
    }

    public static class Location {
        @SerializedName("name") private String name;
        public String getName() { return name; }
    }

    public static class WeatherNow {
        @SerializedName("text") private String text;
        @SerializedName("temperature") private String temperature;
        public String getText() { return text; }
        public String getTemperature() { return temperature; }
    }

    // Cron表达式解析器（简化实现）
    public static class CronExpression {
        private final int hour, minute, second;

        public CronExpression(String cronExpression) {
            String[] parts = cronExpression.split(" ");
            second = Integer.parseInt(parts[0]);
            minute = Integer.parseInt(parts[1]);
            hour = Integer.parseInt(parts[2]);
        }

        public Date getNextExecutionTime(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);

            // 设置为今天的目标时间
            calendar.set(Calendar.HOUR_OF_DAY, hour);
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.SECOND, second);
            calendar.set(Calendar.MILLISECOND, 0);

            // 如果目标时间已过，则推迟到明天
            if (calendar.getTimeInMillis() <= now.getTime()) {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }

            return calendar.getTime();
        }
    }
}